package com.hcyy.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcyy.entity.Cart;
import com.hcyy.entity.Product;
import com.hcyy.entity.User;
import com.hcyy.interceptor.Token;
import com.hcyy.service.CartService;
import com.hcyy.service.ProductService;
import com.hcyy.util.UserUtil;

@Controller
@RequestMapping("/Shop")
public class CartController {
	@Autowired
	private CartService cartService;
	@Autowired
	private ProductService productService;
	@Autowired
	private UserUtil userUtil;
	//加入购物车
	@RequestMapping(value="/Cart/AddCart",method=RequestMethod.POST)
	@ResponseBody
	public boolean addCart(HttpServletRequest request){
		Cart cart=new Cart(); 
		String spid=request.getParameter("spid");//商品ID
		String dwbh=userUtil.findUser(request).getDwbh();
		int FQty=Integer.parseInt(request.getParameter("FQty"));
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		//根据商品ID查询商品信息
		Product product=productService.findProductById(spid,sjid);
		cart.setPihao(product.getProductBal().get(0).getPihao());
		cart.setZhongbz(product.getZhongbz());
//		判断加入购物车数量
		Double price=0.00;
		double priceChl=product.getPriceChl();
		if(priceChl!=0&&FQty<product.getJlgg()){//拆零价不是0，小于件装量
			price=product.getPriceChl();//使用拆零价
		}else{
			price=product.getPrice();//大于等于件装量，使用原价
		}
		cart.setFPrice(price);
		cart.setFQty(FQty);
		cart.setSpid(spid);
		cart.setDwbh(dwbh);
		cart.setSjid(product.getSjid());
		int affectRows = cartService.addCart(cart);
		return affectRows>0?true:false;
	}
	//进入购物车页面
	@RequestMapping("/Cart/Index")
	public String showCart(HttpServletRequest request,Model model){
		String userid=userUtil.findUser(request).getDwbh();
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		List<Cart> cartList=cartService.findCartByUserID(userid,sjid);
		/*for(int i=0;i<cartList.size();i++){
			Double price=cartList.get(i).getFPrice();//购物车中商品的价格
			int FQty=cartList.get(i).getFQty();//购物车中商品的数量
			String spid=cartList.get(i).getSpid();
			Product product=productService.findProductById(spid,sjid);
			int jlgg=product.getJlgg();//商品件装量
			Double newpriceChl=product.getPriceChl();//查询商品的最新价格（拆零价）
			Double newpriceZhj=product.getPrice();//查询商品的最新价格（整件价）
			double newPrice=newpriceZhj;
			if(FQty<jlgg&&newpriceChl!=0){//数量小于件装量，该商品有拆零价
				newPrice=newpriceChl;
			}
			updatePrice(cartList, i, price, newPrice);
		}*/
		model.addAttribute("cartList",cartList);
		model.addAttribute("sjid", sjid);
		return "cart";
	}

	private void updatePrice(List<Cart> cartList, int i, Double price, Double newprice) {
		if(!price.equals(newprice)){//判断价格有变动，执行更行价格
			cartList.get(i).setFPrice(newprice);
			cartList.set(i, cartList.get(i));
			cartService.updateCartPrice(cartList.get(i).getCid(), newprice);//更新购物车商品价格
		}
	}
	private void updatePrice(Cart cart,Double price, Double newprice){
		if(!price.equals(newprice)){//判断价格有变动，执行更行价格
			cart.setFPrice(newprice);
			cartService.updateCartPrice(cart.getCid(), newprice);//更新购物车商品价格
		}
	}
	
	@RequestMapping("/Cart/DelCart")
	@ResponseBody
	public boolean delCart(HttpServletRequest request){
		Long cid=Long.parseLong(request.getParameter("orderdetailid"));
		try {
			cartService.delCart(cid);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@RequestMapping("/Cart/ModCart")
	@ResponseBody
	public boolean modCart(HttpServletRequest request){
		Long cid=Long.parseLong(request.getParameter("orderdetailid"));
		int FQty=Integer.parseInt(request.getParameter("ordernum"));
		double FPrice=Double.parseDouble(request.getParameter("price"));
		try {
			cartService.modCart(cid, FQty,FPrice);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@Token(save=true)
	@RequestMapping("/Order/Index")
	public String accountOrder(String[] idarray,Model model,HttpServletRequest request){
		String dwbh=userUtil.findUser(request).getDwbh();
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		List<Cart> cartList=null;
		cartList=cartService.findCartByCidArray(idarray,dwbh,sjid);
		if(cartList.size()>0){
			for(Cart cart:cartList){
				Double price=cart.getFPrice();//购物车中商品的价格
				String spid=cart.getSpid();
				Product product=productService.findProductById(spid,sjid);
				int FQty=cart.getFQty();//购物车中商品的数量
				int jlgg=product.getJlgg();//商品件装量
				Double newpriceChl=product.getPriceChl();//查询商品的最新价格（拆零价）
				Double newpriceZhj=product.getPrice();//查询商品的最新价格（整件价）
				double newPrice=newpriceZhj;
				if(FQty<jlgg&&newpriceChl!=0){//数量小于件装量，并且有拆零价
					newPrice=newpriceChl;
				}
				updatePrice(cart, price, newPrice);
			}
			model.addAttribute("cartList",cartList);
			return "order";
		}else{
			return "redirect:/Shop/QuickCart?sjid="+sjid;
		}
	}
	
	//快速下单搜索商品
	@ResponseBody
	@RequestMapping(value="/Search",method=RequestMethod.POST)
	public List<Product> searchProduct(HttpServletRequest request){
		String search=request.getParameter("search");
		List<Product> productlist=new ArrayList<Product>();
		String dwbh=null;
		Integer khlb=null;
		try {
			if(request.getSession().getAttribute("user")!=null){
				User user=userUtil.findUser(request);
				dwbh=user.getDwbh();
				khlb=user.getKhlb();
			}
			Integer sjid=(Integer) request.getSession().getAttribute("sjid");
			productlist=productService.findProductBySearch(search.trim(),dwbh,sjid,khlb);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return productlist;
	} 
	
	
}
